$(document).ready(function () {
    var list = $('#List');
    $('.xh-datagrid-toolbar').parseToolbar();
    $('.xh-form').parseForm($('#bt_form_add, #bt_form_edit'));
    /*初始化列表*/
    var assistId = getQueryString('assistId');
    var taskId = getQueryString('taskId');
    // console.log(assistId);
    // console.log(taskId);

    list.initDataGrid(moduleUrl + 'Service/getAssistCatalog?assistId=' + assistId + '&taskId=' + taskId);
    // console.log(moduleUrl + 'Service/getAssistCatalog?assistId=' + assistId + '&taskId=' + taskId);
    //刷新获取目录
    /**************目录操作**********************/

    var flash = setInterval(function flashRow() {

        list.dataGridReload();
        flashTaskStatus(assistId, taskId, function (data) {
            if (data.state < 4) {
                // flag = true;
            } else {
                // flag = false;
                clearInterval(flash);
                if (data.state === 5) {
                    $('#catalog_state').show();
                    $('#catalog_state').text('目录操作超时');
                }
            }
        });

    }, 1000);

    //返回上一目录
    $('#last_catalog').click(function () {
        var text = $('#catalog_current').text();
        var path = getState(text);
        console.log(path);
        var index = path.lastIndexOf('/');
        if (index === 0) {
            index = 1;
        }
        path = path.substring(0, index);
        console.log(path);
        entryCatalog(path, assistId);
    });
    //刷新当前目录
    $('#flash_current_catalog').click(function () {
        flashCurrentCatalog();
    });
    function flashCurrentCatalog() {
        var text = $('#catalog_current').text();
        var path = getState(text);
        path = removeAllSpace(path);
        entryCatalog(path, assistId);
    }


    /**************下载**********************/
    var uploadFlag = false;
    //点击上传选中文件
    $('#btn_file_upload').click(function () {
        //获取选中目录
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert("未选中文件");
        }
        if (row !== null) {
            // console.log(row.name);
            var text = $('#catalog_current').text();
            text = getState(text);
            var path = text + '/' + row.name;
            path = removeAllSpace(path);
            $('#file_upload_status').text('上传状态');
            $('#file_upload_url').text('');
            //上传文件任务
            // uploadCatalogFile(path, assistId);
            var instruction = 'uploadFile("' + path + '")';
            distributeTask(assistId, instruction, function (taskId) {
                console.log('flash upload start');
                $('#btn_file_upload').hide();
                $('#file_upload_url').text('');
                var upload = setInterval(function uploadStatus() {
                    // console.log("flash upload");
                    flashTaskStatus(assistId, taskId, function (data) {
                        // console.log("刷新成功");
                        // console.log(data);
                        //执行中
                        $('#file_upload_status').text('上传状态：执行中');
                        if (data.state === 4) {
                            $('#file_upload_status').text('上传状态：传输中');
                        } else if (data.state === 5) {
                            $('#file_upload_status').text('上传状态：超时');
                            clearInterval(upload);
                        } else if (data.state === 6) {
                            //    返回结果
                            console.log(data.resources);
                            $('#btn_file_upload').show();
                            $('#file_upload_status').text('上传状态：返回结果');
                            var resource = data.resources[0];
                            // console.log(resource);
                            var url = resource.url;
                            // console.log(url);
                            $("#file_upload_url").attr("href", url);
                            $('#file_upload_url').text(url);
                            clearInterval(upload);
                        }
                    });
                }, 1000);
            })
        }
    });

    //文件及文件夹重命名
    $('#btn_file_rename').click(function () {
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert("未选中文件")
        }else {
            var rename = $('#file_rename').val();
            var text = $('#catalog_current').text();
            text = getState(text);
            var path = text + '/' + row.name;
            path = removeAllSpace(path);
            if (rename === null || rename === '') {
                alert("命名为空");
            }
            if (row !== null && rename !== null && rename !== '') {
                //    下发重命名任务任务
                var instruction = 'renameFile("' + path + '","' + rename + '")';
                distributeTask(assistId, instruction, function (taskId) {
                    $('#rename_status').text('命名执行中');
                    console.log('flash rename start');
                    $('#btn_file_rename').hide();
                    var rename = setInterval(function uploadStatus() {
                        // console.log("flash upload");
                        flashTaskStatus(assistId, taskId, function (data) {
                            //执行中
                            $('#rename_status').text('命名执行中');
                            if (data.state === 4 || data.state === 6) {
                                $('#rename_status').text('成功');
                                clearInterval(rename);
                                //刷新当前目录
                                flashCurrentCatalog();
                            } else if (data.state === 5) {
                                $('#rename_status').text('超时');
                                clearInterval(rename);
                            }
                        });
                    }, 1000);
                });
            }
        }
    });


    /**************上传文件到当前目录**********************/
    $('#btn_upload_file').click(function () {
            $('#upload_file_input').click();
            /* if ($('#upload_file_input')[0].files.length === 0) {
             alert("未选择文件")
             }*/

        }
    );

    $('#upload_file_input').change(function () {

        if ($('#upload_file_input')[0].files.length) {
            var list = $('#upload_file_input')[0].files;
            var name = list[0].name;
            if(confirm('确认上传文件'+name+'?')){
                $('#btn_upload_file').hide();
                // var url = 'http://filesoss.yunzuoye.net/XHFileServer/file/upload/SB103014/';
                $('#trans_file_state').text('正在上传文件服务器……');
                uploadFileToServer(list[0], function (result) {
                    if (result.code == 200) {
                        console.log(result);
                        $('#trans_file_state').text('上传文件服务器成功');
                        var fileUrl = result.msg;
                        //    下发任务
                        var text = $('#catalog_current').text();
                        var path = getState(text) + '/' + name;
                        path = removeAllSpace(path);
                        console.log(path);
                        $('#btn_upload_file').show();
                        $('#trans_file_state').text('下发任务');
                        var instruction = 'downloadFile("' + fileUrl + '","' + path + '")';
                        distributeTask(assistId, instruction, function (taskId) {
                            var upload = setInterval(function uploadStatus() {
                                // console.log("flash upload");
                                flashTaskStatus(assistId, taskId, function (data) {
                                    // checkTranslate(data);
                                    $('#trans_file_state').text('传输中');
                                    if (data.state === 4 || data.state === 6) {
                                        $('#trans_file_state').text('操作成功');
                                        clearInterval(upload);
                                        //刷新当前目录
                                        flashCurrentCatalog();
                                    } else if (data.state === 5) {
                                        $('#trans_file_state').text('操作超时');
                                        clearInterval(upload);
                                    }
                                });
                            }, 1000);
                        })
                    } else {
                        $('#trans_file_state').text('上传文件服务器失败');
                        alert(result.error);
                    }
                // uploadFile(url, list[0], function (result) {
                //     result = JSON.parse(result);
                //     if (result.status === 1000) {
                //         console.log(result);
                //         $('#trans_file_state').text('上传文件服务器成功');
                //         var fileUrl = result.uploadFileDTO.fileId;
                //         //    下发任务
                //         var text = $('#catalog_current').text();
                //         var path = getState(text) + '/' + name;
                //         path = removeAllSpace(path);
                //         console.log(path);
                //         $('#btn_upload_file').show();
                //         $('#trans_file_state').text('下发任务');
                //         var instruction = 'downloadFile("' + fileUrl + '","' + path + '")';
                //         distributeTask(assistId, instruction, function (taskId) {
                //             var upload = setInterval(function uploadStatus() {
                //                 // console.log("flash upload");
                //                 flashTaskStatus(assistId, taskId, function (data) {
                //                     // checkTranslate(data);
                //                     $('#trans_file_state').text('传输中');
                //                     if (data.state === 4 || data.state === 6) {
                //                         $('#trans_file_state').text('操作成功');
                //                         clearInterval(upload);
                //                         //刷新当前目录
                //                         flashCurrentCatalog();
                //                     } else if (data.state === 5) {
                //                         $('#trans_file_state').text('操作超时');
                //                         clearInterval(upload);
                //                     }
                //                 });
                //             }, 1000);
                //         })
                //     } else {
                //         $('#trans_file_state').text('上传文件服务器失败');
                //         alert(result.message);
                //     }
                });
            }
        } else {

        }
    });

    /**************安装本地应用**********************/
    $('#btn_install_select_app').click(function () {
        var row = list.datagrid('getSelected');
        var text = $('#catalog_current').text();
        text = getState(text);
        if (row === null) {
            alert('未选择应用文件');
        }

        if (!row.name.endWith('apk')) {
            alert('选择文件并非应用');
        }
        if (row !== null && row.name.endWith('apk')) {
            var path = text + '/' + row.name;
            path = removeAllSpace(path);
            var instruction = 'installAppOffline("' + path + '")';
            distributeTask(assistId, instruction, function (taskId) {
                //
                $('#btn_install_select_app').hide();
                $('#install_status').text('安装执行中');
                var install = setInterval(function () {
                    flashTaskStatus(assistId, taskId, function (data) {
                        //执行中
                        $('#btn_install_select_app').show();
                        // $('#install_status').text('安装执行中');
                        /*if (data.state === 4) {
                         $('#install_status').text('操作成功 正在安装');
                         } else */
                        if (data.state === 6||data.state===4) {
                            $('#install_status').text('安装成功');
                            clearInterval(install);
                        } else if (data.state === 5) {
                            $('#install_status').text('操作超时');
                            clearInterval(install);
                        }
                    });
                }, 1000);
            })
        }

    });

    /**************删除文件**********************/
    $('#btn_file_delete').click(function () {
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert('未选择文件');
        }
        if (row !== null) {
            if (confirm("确认删除？")) {
                var text = $('#catalog_current').text();
                text = getState(text);
                var path = text + '/' + row.name;
                path = removeAllSpace(path);
                var instruction = 'executeCmd("rm -r ' + path + '")';
                //下发任务
                distributeTask(assistId, instruction, function (taskId) {
                    $('#btn_file_delete').hide();
                    var del = setInterval(function () {
                        flashTaskStatus(assistId, taskId, function (data) {
                            //执行中
                            $('#btn_file_delete').show();
                            $('#delete_file_status').text('删除执行中');
                            if (data.state === 6 || data.state == 4) {
                                $('#delete_file_status').text('删除成功');
                                clearInterval(del);
                                flashCurrentCatalog();
                            } else if (data.state === 5) {
                                $('#delete_file_status').text('操作超时');
                                clearInterval(del);
                            }
                        });
                    }, 1000);
                });
            }
        }


    });

    /**************协助状态**********************/
        //定时获取协助是否存活
    var alive = setInterval(function getAssistAlive() {
            getAliveAssist(assistId, $('#device_alive'),function () {
                $('#bt_Task_Add').setButtonDisable('eu');
                $('#assist_quit').attr('hidden', 'hidden');
                clearInterval(alive);
            });
        }, 5000);
    //获取协助状态
    var text = $('#assist_state').text();
    var state = getState(text);
    /*    if (state === '准备' || state === '进行中') {
     getAliveAssist(id);
     }*/
    if (state === '完成' || state === '超时') {
        $('#bt_Task_Add').setButtonDisable('eu');
        $('#assist_quit').attr('hidden', 'hidden');
        clearInterval(alive);
        // clearInterval(flash);
    }
    //退出协助
    $('#assist_quit').click(function () {
        assistQuit(assistId, function () {
            location.reload();
        })
    });
    $('#bt_form_back').click(function () {
        $.overtFun.clickBackForm();
    });
    $('#bt_form_reset').click(function () {
        $.overtFun.clickResetForm();
    });

});

function entryLineCatalog(line) {
    var name = $(line).closest('tr').children('[field=name]').text();
    var assistId = getQueryString('assistId');
    var text = $('#catalog_current').text();
    // var path = getState(text) + "/" + name;
    var path = getState(text);
    path = removeAllSpace(path);
    if (path === '/') {
        path = path + name;
    } else {
        path = path + '/' + name;
    }
    entryCatalog(path, assistId);
}
//进入目录
function entryCatalog(path, assistId) {
    // var path = '/sdcard/xuehai';
    var instruction = 'getFileTree("' + path + '")';
    distributeTask(assistId, instruction, function (taskId) {
        var catalogUrl = moduleUrl + "assist/catalog?assistId=" + assistId + "&taskId=" + taskId;
        // window.top.xhTop.createNewTab($title, $catalogUrl);
        window.location.href = catalogUrl;
    });

}
function getState(text) {
    // var text = $('#assist_state').text();
    if (text !== null || text.length !== 0) {
        var array = text.split('：');
        // console.log(array);
        return array[1];
    }
}

